package net.sync.test1;

import java.util.concurrent.locks.ReentrantLock;

public class FairLockTest implements Runnable {
    /**
     * 所谓公平锁，就是按照时间先后顺序，使先等待的线程先得到锁，而且，公平锁不会产生饥饿锁，也就是只要排队等待，
     * 最终能等待到获取锁的机会。使用重入锁（默认是非公平锁）创建公平锁：
     * public ReentrantLock(boolean fair) {
     *     sync = fair ? new FairSync() : new NonfairSync();
     * }
     */
    public static ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                System.err.println(Thread.currentThread().getName() + "获取到了锁！");
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FairLockTest test = new FairLockTest();
        Thread t1 = new Thread(test, "线程1");
        Thread t2 = new Thread(test, "线程2");
        t1.start();
        t2.start();
        /**
         * 可以发现，t1和t2交替获取到锁。如果是非公平锁，会发生t1运行了许多遍后t2才开始运行的情况。
         */
    }
}
